package shop.file.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import shop.common.entity.Image;
import shop.file.mapper.ImageMapper;
import shop.file.service.ImageService;

import java.io.IOException;

@Service
public class ImageServiceImpl extends ServiceImpl<ImageMapper, Image> implements ImageService {
    
    @Override
    public Image uploadImage(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }
        
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

        Image image = new Image();
        image.setId(String.valueOf(IdWorker.getId()));
        image.setSuffix(suffix);
        try {
            image.setData(file.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        baseMapper.insert(image);
        
        return image;
    }
    
}